package ug.co.icom.kyazze.healthticket.mongoHQ;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import ug.co.icom.kyazze.healthticket.data.AppData;
import ug.co.icom.kyazze.healthticket.data.QueryBuilder;

public class MongoHQAppData{

	static BasicDBObject user = null;
	static String OriginalObject = "";
	static String server_output = null;
	static String temp_output = null;
	static AppData appdata;

	public AppData getAppData() {
		try {

			QueryBuilder qb = new QueryBuilder();
			URL url = new URL(qb.buildAppDataQuery());
			HttpURLConnection conn = (HttpURLConnection) url
					.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));

			//System.out.println("Output from Server .... \n");
			while ((temp_output = br.readLine()) != null) {
				server_output = temp_output;
			}

			// Remove square brackets
			OriginalObject = server_output.substring(1, server_output.length() - 1);

			Object o = com.mongodb.util.JSON.parse(OriginalObject);

			DBObject userObj = (DBObject) o;
			
			AppData temp = new AppData();

			temp.Email = userObj.get("email").toString();
			temp.Password = userObj.get("lp").toString();
			
			appdata = temp;

		}catch (Exception e) {
			e.printStackTrace();
		}

		return appdata;
	}

}
